import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import type { AsyncThunk, ActionReducerMapBuilder, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getUserFlow, type GetUserFlowParams } from './userFlowAPI'
import { DataType } from "@/pages/UserFlow/Table";
import dayjs from '@/utils/dayjs'
import { TZ } from "@/utils/env";
import { v4 } from "uuid";

const threeDaysAgoStart = dayjs().tz(TZ).subtract(3, 'day').unix();
const todayEnd = dayjs().tz(TZ).unix();

interface InitialState {
  params: GetUserFlowParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data: Res | undefined,
    params?: GetUserFlowParams
  }
}

const initialState:InitialState = {
  params: {
    page: 1,
    page_size: 10,
    start_t: threeDaysAgoStart,
    end_t: todayEnd,
    source: "",
    username: "",
    query_user_id: ""
  },
  table: {
    status: "init",
    data: undefined,
  }
};

type Res = {
  data: {
    total:number,
    page: number,
    page_data: DataType[]
  }
}
type AsyncRes = {
  data: Res,
  params: GetUserFlowParams
}
export const getUserFlowAsync:AsyncThunk<AsyncRes, GetUserFlowParams, {}> = createAsyncThunk<AsyncRes, GetUserFlowParams, {}>(
  "userFlow/getUserFlowAsync",
  async (params) => {
    const res:Res = await getUserFlow(params);
    return {
      data: res,
      params
    };
  }
);
const tableStatus:(builder:ActionReducerMapBuilder<InitialState>)=>void = (builder:ActionReducerMapBuilder<InitialState>):void => {
  builder
    .addCase(getUserFlowAsync.pending, (state:InitialState):void => {
      state.table.status = "loading";
    })
    .addCase(getUserFlowAsync.fulfilled, (state:InitialState, action:PayloadAction<AsyncRes>):void => {
      state.table.status = "success";
      if(Array.isArray(action.payload?.data?.data?.page_data)){
        action.payload.data.data.page_data.forEach(i => i.uuid = v4())
      }
      state.table.data = action.payload.data;
      state.table.params = action.payload.params
    })
    .addCase(getUserFlowAsync.rejected, (state:InitialState):void => {
      state.table.status = "error";
    });
};

type Reducers = {
  changeParams:(state:InitialState, action:PayloadAction<Partial<GetUserFlowParams>>)=>void,
}
type Selectors = {}
const userFlowSlice:Slice<InitialState,Reducers,'userFlow','userFlow',Selectors> = createSlice<InitialState, Reducers, 'userFlow', Selectors, 'userFlow'>({
  name: "userFlow",
  initialState,
  reducers: {
    changeParams(state:InitialState, action:PayloadAction<Partial<GetUserFlowParams>>):void {
      state.params = {
        ...state.params,
        ...action.payload,
      };
    }
  },
  extraReducers(builder:ActionReducerMapBuilder<InitialState>):void {
    tableStatus(builder);
  },
});

export const { changeParams }:typeof userFlowSlice.actions = userFlowSlice.actions;

export default userFlowSlice.reducer;
